package com.u1s1.controller;

import com.sun.org.apache.xpath.internal.operations.Mod;
import com.u1s1.entity.Activity;
import com.u1s1.entity.Users;
import com.u1s1.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;



import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/ado")
public class ActivityController {
    @Autowired
    private ActivityService activityService;

    @RequestMapping(path = {"/query"})
    private String query(Model model) {

//        username.replaceAll("[`~!@#$^&*()=|{}':;',\\[\\].<>TRJdspfdsnvpod","");   我不知道正则应该怎么写来防止sql注入

        model.addAttribute("list",activityService.selectSelective(null));

        return "activityInfo";
    }

    @RequestMapping(path = {"/update"})
    private String update(int id, Model model) {
        Activity activity = activityService.selectByPrimaryKey(id);
        model.addAttribute("activity", activity);
        return "update1";
    }

    @RequestMapping(path = {"/updatedo"})
    private String updatedo(Activity newActivity, Model model) {
        int id = newActivity.getId();

        Activity oldActivity = activityService.selectByPrimaryKey(id);

        String oldActivityName = oldActivity.getActivityName();
        Activity tempActivity = new Activity();
        tempActivity.setActivityName(newActivity.getActivityName());

        List<Activity> list = activityService.selectSelective(tempActivity);
        if (!newActivity.getActivityName().equals(oldActivityName) && list.size() > 0) {
            model.addAttribute("note", "该用户名已存在或与原有用户名相同");
            return "forward:/ado/update";
        }

        int rows = activityService.updateByPrimaryKeySelective(newActivity);

        if (rows > 0) {
            return "redirect:/ado/query";
        } else {
            return "redirect:error.jsp";
        }
    }

    @RequestMapping(path = {"/delete"})
    private String delete(int id) {
        int rows = activityService.deleteByPrimaryKey(id);
        System.out.println(rows);
        if (rows > 0) {
            return "redirect:/ado/query";
        } else {
            return "error";
        }
    }

    @RequestMapping("/adddo")
    private String adddo(Model model){
        return "/activity/add";
    }

    @RequestMapping(path = {"/add"})
    private String add(Activity activity) {

//        if (usersService.getCountByName(user.getName()) > 0) {
//            req.setAttribute("note", "用户名已存在");
//            req.getRequestDispatcher("/add.jsp").forward(req, resp);
//            return;
//        }

        int rows = activityService.insertSelective(activity);
        if (rows > 0) {
            return "redirect:/ado/query";
        } else {
            return "error";
        }
    }
}
